// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let data = event.data
  if (event.data) {
    data.time = new Date(data.time)
    let mes = await db.collection('money_list').add({
      data: data
    })

    data._id = mes._id
    await db.collection('gods').where({
      _openid: wxContext.OPENID,
    }).update({
      data: {
        'publish.money': _.push(data),
        btList: _.push({
          name: "发布悬赏任务",
          time: new Date(),
          num: 5
        })
      }
    })
    return data

  } else if (event.skip || event.skip == 0) {

    if (event.date == "") {
      return db.collection('money_list').aggregate().match({
        // _openid: _.not(_.eq(wxContext.OPENID))
        _openid: _.not(_.eq("00"))
      }).sort({
        time: -1
      }).skip(event.skip).limit(10).end()
    } else {
      let time = new Date(event.date).setTime(new Date(event.date).getTime() + 24 * 60 * 60 * 1000);
      return await db.collection('money_list').where({
        'time': _.and(_.gte(new Date(event.date)), _.lt(new Date(time))),
        // _openid: _.not(_.eq(wxContext.OPENID))
      }).skip(event.skip).limit(10).get()
    }




    let time = new Date(event.date).setTime(new Date(event.date).getTime() + 24 * 60 * 60 * 1000);
    return await db.collection('lostGoods_list').where({
      'time': _.and(_.gte(new Date(event.date)), _.lt(new Date(time))),
      _openid: _.not(_.eq(message.OPENID))
    }).skip(event.skip).limit(10).get()

    return db.collection('money_list').aggregate().sort({
      time: -1
    }).skip(event.skip).limit(10).end()
  }
}